"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 资源池化
Case Name   : 开启事务,设置事务隔离级别为READ COMMITTED,在事务中进行增删改的操作,提交后回滚
Create At   : 2023.5
Owner       : opentestcase009
Description :
    1、查看集群状态
    2、创建表,插入数据
    3、在主机和备机分别开启事务,设置事务隔离级别为READ COMMITTED,在主机事务1中进行增删改的操作,提交后回滚
    4、清理环境
Expect      :
    1、集群状态正常,数据库节点状态正常
    2、建表成功,插入数据成功
    3、在事务1提交后,事务2查询可见commit的数据,回滚后数据和commit后一致
    4、清理环境成功
History     :
"""

import os
import unittest

from testcase.utils.ComThread import ComThread
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class SharedStorage(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.constant = Constant()
        self.comsh = CommonSH('PrimaryDbUser')
        self.s1_comsh = CommonSH('Standby1DbUser')
        self.t_name = 't_dms_page_002'

    def test_shared_storage(self):
        text = '-----step1:查看集群状态; expect:集群状态正常-----'
        self.log.info(text)

        status = self.comsh.exec_cm_ctl(mode='query', param='-Cv')
        self.log.info(status)
        self.assertIn('cluster_state   : Normal', status, '执行失败' + text)

        text = '-----step2:创建表,插入数据; expect:建表成功,插入数据成功-----'
        self.log.info(text)

        sql = f"create table {self.t_name}(id int,name varchar,salary int) " \
              f"with(segment=on);" \
              f"insert into {self.t_name} values(generate_series(20,50)," \
              f"'local_'||generate_series(20,50),60000);" \
              f"select count(*) from {self.t_name};"
        self.log.info(sql)
        res = self.comsh.execut_db_sql(sql)
        self.log.info(res)
        self.assertTrue(self.constant.CREATE_TABLE_SUCCESS in res
                        and self.constant.INSERT_SUCCESS_MSG in res,
                        '执行失败' + text)
        self.assertEqual('31', res.splitlines()[-2].strip(), '执行失败' + text)

        text = '-----step3:在主机和备机分别开启事务,设置事务隔离级别为READ COMMITTED,在主机事务1中' \
               '进行增删改的操作,提交后回滚; expect:在事务1提交后,事务2查询数据一致,rollback后数据一致-----'
        self.log.info(text)

        sql_1 = f'''start transaction isolation level read committed;
            insert into {self.t_name} values(66,'new_local',66666);
            update {self.t_name} set salary=88888 where id=33;
            delete from {self.t_name} where id < 30;
            select count(*) from {self.t_name};
            select pg_sleep(3);
            end;
            select pg_sleep(3);
            rollback;'''
        session_1 = ComThread(self.comsh.execut_db_sql,
                              args=(sql_1,))
        session_1.setDaemon(True)
        session_1.start()

        sql_2 = f'''select pg_sleep(1);
            start transaction isolation level read committed;
            select count(*) from {self.t_name};
            select pg_sleep(3);
            select count(*) from {self.t_name};
            select pg_sleep(3);
            select count(*) from {self.t_name};
            commit;'''
        session_2 = ComThread(self.s1_comsh.execut_db_sql,
                              args=(sql_2,))
        session_2.setDaemon(True)
        session_2.start()

        session_2.join()
        session_2_result = session_2.get_result()
        self.log.info(session_2_result)

        self.log.info('-----事务1提交前事务2执行结果-----')
        session2_1 = session_2_result.splitlines()[8].strip()
        self.log.info(session2_1)

        self.log.info('-----事务1提交后事务2执行结果-----')
        session2_2 = session_2_result.splitlines()[-14].strip()
        self.log.info(session2_2)

        self.log.info('-----事务1回滚后事务2执行结果-----')
        session2_3 = session_2_result.splitlines()[-4].strip()
        self.log.info(session2_3)

        session_1.join()
        session_1_result = session_1.get_result()
        self.log.info(session_1_result)

        self.assertEqual('31', session2_1, '事务1提交前数据不相等')
        self.assertEqual('22', session2_2, '事务1提交后数据不相等')
        self.assertEqual('22', session2_3, '事务1回滚后数据不相等')

    def tearDown(self):
        text = '-----step4:清理环境,删除表; expect:清理环境成功-----'
        self.log.info(text)

        clear = f'''drop table {self.t_name} cascade;'''
        self.log.info(clear)
        clear_res = self.comsh.execut_db_sql(clear)
        self.log.info(clear_res)

        self.assertIn(self.constant.DROP_TABLE_SUCCESS, clear_res,
                      '执行失败' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
